package com.example.backend.controller;

import com.example.backend.dto.LlmDto;
import com.example.backend.service.LlmService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;

@RestController
@RequestMapping("/llm")
@RequiredArgsConstructor
public class LlmController {

    private final LlmService llmService;

    @PostMapping("/chat")
    public Mono<ResponseEntity<LlmDto.ChatResponse>> chat(@Valid @RequestBody LlmDto.ChatRequest request) {
        return llmService.chat(request)
                .map(ResponseEntity::ok)
                .onErrorResume(error -> {
                    LlmDto.ErrorResponse errorResponse = LlmDto.ErrorResponse.builder()
                            .error("LLM服务调用失败")
                            .details(error.getMessage())
                            .build();
                    return Mono.just(ResponseEntity.internalServerError().body(
                            LlmDto.ChatResponse.builder()
                                    .message(errorResponse.getError() + ": " + errorResponse.getDetails())
                                    .build()
                    ));
                });
    }
}
